package com.magic.blog.template;

import com.magic.blog.common.templates.DirectiveHandler;
import com.magic.blog.common.templates.TemplateDirective;
import com.magic.blog.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import java.util.*;


@Component
public class HotsTemplate extends TemplateDirective {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public String getName() {
        return "hots";
    }

    @Override
    public void execute(DirectiveHandler handler) throws Exception {
        String weekRangeKey = "week:rank";
        Set<ZSetOperations.TypedTuple> typedTuples = redisUtil.getZSetRank(weekRangeKey, 0, 6);

        List<Map> hotPost = new ArrayList<>();

        for(ZSetOperations.TypedTuple typedTuple:typedTuples){
            Map<String,Object> map = new HashMap<>();

            Object value = typedTuple.getValue();
            String postKey = "rank:post:"+value;
            map.put("id",value);
            map.put("title",redisUtil.hget(postKey,"post:title"));
            map.put("commentCount",typedTuple.getScore());

            hotPost.add(map);
        }

        handler.put(RESULTS,hotPost).render();
    }
}
